package com.gdc.cloud.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Date;

/**
 * Description: 自定义全局 的 过滤器
 *      注意：必须实现 GlobalFilter，Ordered接口
 *
 * @author: gdc
 * @date: 2021/2/3
 * @version 1.0
 */
@Slf4j
@Component
public class MyLogGatewayFilter implements GlobalFilter, Ordered {

    /**
     * 对请求 的参数进行过滤，如果包含 用户名（uname）放行，否则直接返回
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        log.info("********** welcome in MyLogGatewayFilter: {}", new Date());
        String uname = exchange.getRequest().getQueryParams().getFirst("uname");
        if (StringUtils.isEmpty(uname)) {
            log.error("********** 用户名称为null, 非法用户");
            exchange.getResponse().setStatusCode(HttpStatus.NOT_ACCEPTABLE);
            return exchange.getResponse().setComplete();
        }
        return chain.filter(exchange);
    }

    /**
     * 设置 过滤的 优先级，数字越小，优先级越高
     */
    @Override
    public int getOrder() {
        return 0;
    }
}
